<template>
  <div class="home">
    <!-- 轮播图或横幅 -->
    <el-card class="banner-card">
      <div class="banner">
        <h2 v-if="currentUser && currentUser.name">欢迎，{{ currentUser.name }}！</h2>
        <h2 v-else>欢迎来到二手教材交易平台</h2>
        <p>买卖教材，资源共享，让知识传递更便捷</p>
        <el-button type="primary" size="large" @click="$router.push('/textbooks')">
          浏览教材
        </el-button>
        <el-button type="success" size="large" @click="$router.push('/publish')">
          发布教材
        </el-button>
        <span></span>
      </div>
    </el-card>

  <!-- 科目分类 -->
  <el-card class="categories-card">
    <template #header>
      <div class="card-header">
        <span>科目分类</span>
      </div>
    </template>
    <div class="categories" v-loading="categoriesLoading">
      <div 
        class="category-item"
        v-for="category in categories"
        :key="category.id"
        @click="goToCategory(category.id, category.name)"
      >
        <div class="category-icon">
          <el-icon><Grid /></el-icon>
        </div>
        <div class="category-name">{{ category.name }}</div>
      </div>
    </div>
  </el-card>

  <!-- 热门教材 -->
    <el-card class="textbooks-card">
      <template #header>
        <div class="card-header">
          <span>热门教材</span>
          <el-button type="text" @click="$router.push('/textbooks')">查看更多 ></el-button>
        </div>
      </template>
      <div class="textbooks" v-loading="textbooksLoading">
        <el-empty v-if="!textbooksLoading && textbooks.length === 0" description="暂无教材" />
        <div 
          class="textbook-item" 
          v-for="textbook in textbooks" 
          :key="textbook.id"
          @click="goToDetail(textbook.id)"
        >
          <div class="textbook-image">
            <el-image 
              :src="getTextbookImage(textbook.images, textbook.category_name)" 
              fit="cover"
              :lazy="true"
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <el-tag :type="getConditionType(textbook.condition)" class="condition-tag">
              {{ getConditionText(textbook.condition) }}
            </el-tag>
          </div>
          <div class="textbook-info">
            <h3 class="textbook-title">{{ textbook.title }}</h3>
            <p class="textbook-author">{{ textbook.author }}</p>
            <div class="textbook-meta">
              <span class="textbook-category">{{ textbook.category_name }}</span>
              <span class="textbook-seller">卖家: {{ textbook.seller_name }}</span>
            </div>
            <div class="textbook-price">
              <span class="price">¥{{ textbook.price }}</span>
              <span class="original-price" v-if="textbook.original_price">
                原价: ¥{{ textbook.original_price }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Picture } from '@element-plus/icons-vue'
import { textbookApi } from '../api/textbook'
import { Grid } from '@element-plus/icons-vue'

const router = useRouter()
const textbooks = ref([])
const categories = ref([])
const textbooksLoading = ref(false)
const categoriesLoading = ref(false)
const currentUser = ref(null)

// 获取分类列表
const loadCategories = async () => {
  categoriesLoading.value = true
  try {
    const response = await textbookApi.getCategories()
    if (response.success) {
      categories.value = response.data
    }
  } catch (error) {
    console.error('加载分类失败:', error)
  } finally {
    categoriesLoading.value = false
  }
}

// 获取热门教材
const loadTextbooks = async () => {
  textbooksLoading.value = true
  try {
    const response = await textbookApi.getTextbooks({
      page: 1,
      pageSize: 8,
      status: 'on_sale'
    })
    if (response.success) {
      textbooks.value = response.data
    }
  } catch (error) {
    console.error('加载教材失败:', error)
  } finally {
    textbooksLoading.value = false
  }
}

// 获取教材图片
const getTextbookImage = (images, categoryName) => {
  if (images && images.length > 0) {
    return images[0];
  }
  // 根据类别返回默认图片
  const categoryImages = {
    '数学': '/src/assets/images/math_textbook.svg',
    '英语': '/src/assets/images/english_textbook.svg',
    '计算机': '/src/assets/images/computer_textbook.svg',
    '物理': '/src/assets/images/physics_textbook.svg'
  };
  return categoryImages[categoryName] || '';
};

// 获取成色类型
const getConditionType = (condition) => {
  const types = {
    'new': 'success',
    'like_new': 'info',
    'good': '',
    'fair': 'warning',
    'poor': 'danger'
  }
  return types[condition] || ''
}

// 获取成色文本
const getConditionText = (condition) => {
  const texts = {
    'new': '全新',
    'like_new': '九成新',
    'good': '八成新',
    'fair': '七成新',
    'poor': '六成新'
  }
  return texts[condition] || '未知'
}

// 跳转到详情
const goToDetail = (id) => {
  router.push(`/textbooks/${id}`)
}

// 跳转到分类页面
const goToCategory = (id, name) => {
  router.push({ path: '/textbooks', query: { category_id: id, category_name: name } })
}

onMounted(() => {
  loadCategories()
  loadTextbooks()
  
  // 从本地存储获取用户信息
  const userStr = localStorage.getItem('user')
  if (userStr) {
    try {
      currentUser.value = JSON.parse(userStr)
    } catch (e) {
      console.error('解析用户信息失败:', e)
    }
  }
})
</script>

<style scoped>
.home {
  max-width: 1200px;
  margin: 0 auto;
}

.banner-card {
  margin-bottom: 20px;
}

.categories-card {
  margin-bottom: 20px;
}

.categories {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 15px;
}

.category-item {
  text-align: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.category-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.category-icon {
  font-size: 32px;
  margin-bottom: 10px;
  color: #667eea;
}

.category-name {
  font-size: 14px;
  color: #303133;
}

.banner {
  text-align: center;
  padding: 40px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 8px;
}

.banner h2 {
  margin: 0 0 10px 0;
  font-size: 32px;
}

.banner p {
  margin: 0 0 20px 0;
  font-size: 16px;
  opacity: 0.9;
}

.textbooks-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}



.textbooks {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}

.textbook-item {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.textbook-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.textbook-image {
  position: relative;
  width: 100%;
  height: 200px;
  overflow: hidden;
  background-color: #f5f5f5;
}

.textbook-image .el-image {
  width: 100%;
  height: 100%;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f5f5;
  color: #909399;
  font-size: 30px;
}

.condition-tag {
  position: absolute;
  top: 10px;
  right: 10px;
}

.textbook-info {
  padding: 15px;
}

.textbook-title {
  font-size: 16px;
  font-weight: bold;
  margin: 0 0 5px 0;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.textbook-author {
  font-size: 14px;
  color: #909399;
  margin: 0 0 10px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.textbook-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
  margin-bottom: 10px;
}

.textbook-price {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price {
  font-size: 20px;
  font-weight: bold;
  color: #f56c6c;
}

.original-price {
  font-size: 12px;
  color: #909399;
  text-decoration: line-through;
}
</style>